package com.xxkk.spring_boot_web.sdk.KBZ.utils;

import cn.hutool.core.codec.Base64;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class RSAUtil {
    public static String decrypt(String str, String str2) {
        PrivateKey privateKey = getPrivateKey(str2);
        try {
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(2, privateKey);
            return new String(cipher.doFinal(Base64.decode(str)), "UTF-8");
        } catch (Exception unused) {
            return null;
        }
    }

    public static String encrypt(String str, String str2) {
        PublicKey publicKey = getPublicKey(str2);
        try {
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(1, publicKey);
            return Base64.encode(cipher.doFinal(str.getBytes()));
        } catch (Exception unused) {
            return null;
        }
    }

    public static PrivateKey getPrivateKey(String str) {
        try {
            return KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(Base64.decode(str)));
        } catch (Exception unused) {
            return null;
        }
    }

    public static PublicKey getPublicKey(String str) {
        try {
            return KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(Base64.decode(str)));
        } catch (Exception unused) {
            return null;
        }
    }
}
